package com.goal98.team.services

import javax.mail.MessagingException

import org.springframework.mail.MailException
import org.springframework.mail.SimpleMailMessage
import javax.mail.internet.MimeMessage
import org.springframework.mail.javamail.MimeMessageHelper
import org.codehaus.groovy.grails.plugins.springsecurity.AuthorizeTools

/**
 * Simple service for sending emails.
 *
 * Work is planned in the Grails roadmap to implement first-class email
 * support, so there's no point in making this code any more sophisticated.
 *
 * @author Haotian Sun
 */
class EmailerService {

    boolean transactional = false

    def mailSender
    def mailMessage // a "prototype" email instance

    /**
     * Send a list of emails.
     *
     * @param mails a list of maps
     */
    def sendEmails(mails) {

        // Build the mail messages
        def messages = []
        for (mail in mails) {
            // create a copy of the default message
            def message = new SimpleMailMessage(mailMessage)
            message.to = mail.to
            message.text = mail.text
            message.subject = mail.subject
            messages << message
        }

        // Send them all together
        try {
            mailSender.send(messages as SimpleMailMessage[])
        }
        catch (MailException e) {
            log.error "Failed to send emails: $e.message", e
        }
        catch (MessagingException e) {
            log.error "Failed to send emails: $e.message", e
        }
    }

    def sendHtmlEmails(mails) {

        def messages = []
        for (mail in mails) {

            final def isMultiPart = true
            final def isHtml = true

            MimeMessage message = mailSender.createMimeMessage()
            MimeMessageHelper helper = new MimeMessageHelper(message, isMultiPart, 'UTF-8');
            helper.setFrom(AuthorizeTools.securityConfig.security.mailFrom)
            helper.setTo(mail.to)
            helper.setText(mail.text, isHtml)
            helper.subject = mail.subject
            messages << message
        }

        try {
            mailSender.send(messages as MimeMessage[])
        }
        catch (MailException e) {
            log.error "Failed to send emails: $e.message", e
        }
        catch (MessagingException e) {
            log.error "Failed to send emails: $e.message", e
        }
    }

    def sendTestMail(emailContent) {
        def email = [
                to: ['liuchao36@gmail.com'],
                subject: "Goal98 Team manager Started.",
                text: emailContent
        ]
        sendHtmlEmails([email])
    }
}
